package com.shengwei.truck.driver.view.ui.home;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.google.android.material.appbar.AppBarLayout;
import com.shengwei.truck.driver.socket.SocketManager;
import com.shengwei.truck.driver.socket.SocketService;
import com.shengwei.truck.driver.utils.MyToast;
import com.shengwei.truck.driver.view.ui.app.MyApplication;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.MyConstant;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.task.JsonTaskListData;
import com.shengwei.truck.driver.bean.task.TaskItem;
import com.shengwei.truck.driver.databinding.FragmentHomeBinding;
import com.shengwei.truck.driver.utils.DateTimeUtils;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.utils.SPUtils;
import com.shengwei.truck.driver.utils.glide.GlideImagesLoader;
import com.shengwei.truck.driver.view.adapter.task.TaskListAdapter;
import com.shengwei.truck.driver.view.selfview.stepview.StepAdapter;
import com.shengwei.truck.driver.view.selfview.stepview.StepData;
import com.shengwei.truck.driver.view.ui.BaseFragment;
import com.shengwei.truck.driver.view.ui.MainActivity;
import com.shengwei.truck.driver.view.ui.mine.msgCenter.MsgCenterActivity;
import com.shengwei.truck.driver.view.ui.task.pounds.PostPoundsListActivity;
import com.shengwei.truck.driver.view.ui.settings.SettingsActivity;
import com.shengwei.truck.driver.view.ui.task.TaskDetailActivity;
import com.shengwei.truck.driver.vm.HomeViewModel;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.youth.banner.BannerConfig;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/**
 * 首页
 */
public class HomeFragment extends BaseFragment<HomeViewModel, FragmentHomeBinding> implements View.OnClickListener {
    private String TAG = "HomeFragment";
    private static final int PULL_REFRESH = 0; //下拉刷新
    private static final int LOAD_MORE = 1;  //加载更多
    private static final int GET_CUR_TASK = 2;  //获取当前正在进行的任务
    private TaskListAdapter mAdapter;
    private List<TaskItem> mTaskList = new ArrayList<>();
    public static boolean isTaskListEmpty = true;
    private static final String ARG_SECTION_NUMBER = "section_number";
    int pageNum = 0; //索引从0开始表示第一页
    int pageSize =8;
    int currentOperate = PULL_REFRESH; //0表示下拉刷新,1表示加载更多
    HomeViewModel homeViewModel;
    TaskItem mCurTaskItem;
    private String mCarNum; //车牌号，进入磅单页面传过去
    private ArrayList<StepData> mDataList;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root =  super.onCreateView(inflater,container,savedInstanceState);
        homeViewModel = (HomeViewModel) ViewModelProviders.of(this).get(HomeViewModel.class);
        initView();
        initLiveDataObersve();
        return root;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        MyLogCat.i(TAG,"onCreate");
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        MyLogCat.i(TAG,"onDestroyView");
        super.onDestroyView();
    }

    @Override
    public void onStop() {
        MyLogCat.i(TAG,"onStop");
        super.onStop();
    }



    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
    @Override
    public int getContentViewId() {
        return R.layout.fragment_home;
    }

    /**
     * 初始化UI控件
     */
    private void initView() {
        setToolBar(false,false,"");
        initBanner();
        intStepData();
        initRecyclerview();
        mDataBinding.btDoTask.setOnClickListener(this);
        mDataBinding.tvQrCode.setOnClickListener(this);
        mDataBinding.tvPostPounds.setOnClickListener(this);
        mDataBinding.msgCenterLayout.setOnClickListener(this);
        mDataBinding.tvSettings.setOnClickListener(this);
        mDataBinding.curTaskLayout.setOnClickListener(this);
        //判断是否是第一次开启应用
        boolean isFirstOpen = SPUtils.getBoolean(getActivity(), MyConstant.FIRST_OPEN);
        if (isFirstOpen) {
            refreshProgressByState(-2,null);  //当前任务信息布局将显示“ 欢迎 UI”
        }
    }


    /**
     * 各阶段上的标注文字
     */
    private void intStepData() {
        StepData data1 = new StepData();
        data1.setStepText("已接");
        StepData data2 = new StepData();
        data2.setStepText("提货");
        StepData data3 = new StepData();
        data3.setStepText("运输");
        StepData data4 = new StepData();
        data4.setStepText("磅单");
        StepData data5 = new StepData();
        data5.setStepText("完成");
        mDataList = new ArrayList<>();
        mDataList.add(data1);
        mDataList.add(data2);
        mDataList.add(data3);
        mDataList.add(data4);
        mDataList.add(data5);

        //StepView与Activity通信，通过接口回调的方式
        mDataBinding.stepView.setStepAdapter(new StepAdapter() {
            @Override
            public int getCount() {
                return mDataList.size();
            }
            @Override
            public List<StepData> getData() {
                return mDataList;
            }
        });

        mDataBinding.stepView.setSelectPosition(0);
    }



    @Override
    public void onStart() {
        MyLogCat.i(TAG,"onStart");
        super.onStart();
    }

    /**
     * 刷新首页所有数据
     */
    public void refreshAllData() {

        mViewModel.getCurTask(); //当前进行的任务
        refreshTaskList();//所有未开始的任务列表
        mViewModel.getUnReadNum();// 消息未读数
    }

    /**
     * 下拉刷新数据,获取当前任务，未开始任务列表，消息数
     */
    private SwipeRefreshLayout.OnRefreshListener mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshAllData();
        }
    };


    /**
     * 初始化banner配置，样式，文字颜色等
     */
    private void initBanner() {
        /**
         *     public static final int NOT_INDICATOR = 0;        没有title与点点
         *     public static final int CIRCLE_INDICATOR = 1;      点点水平居中，无title
         *     public static final int NUM_INDICATOR = 2;          1/3,2/3在右下角且背景是圆形半透明，无title
         *     public static final int NUM_INDICATOR_TITLE = 3;     1/3,2/3在右下角无背景，title在左边
         *     public static final int CIRCLE_INDICATOR_TITLE = 4;       点点水平居中，title在点点的下一行且背景是半透明
         *     public static final int CIRCLE_INDICATOR_TITLE_INSIDE = 5;  点点在右，标题在左，整个在一个矩形半透明条幅上。
         *     当 CIRCLE_INDICATOR时，设置mDataBinding.banner.setIndicatorGravity(BannerConfig.RIGHT)才能起作用;
         */

        mDataBinding.banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mDataBinding.banner.setIndicatorGravity(BannerConfig.RIGHT);
        //设置图片加载器
        mDataBinding.banner.setImageLoader(new GlideImagesLoader());

        List<Integer> images = new ArrayList<>();
        images.add(R.drawable.banner4);
        images.add(R.drawable.banner5);
        images.add(R.drawable.banner6);

        mDataBinding.banner.setImages(images);
        //设置banner动画效果
       // mDataBinding.banner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        mDataBinding.banner.isAutoPlay(true);
        //设置轮播时间
        mDataBinding.banner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        //banner设置方法全部调用完毕时最后调用
        mDataBinding.banner.start();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        MyLogCat.i(TAG,"hidden="+hidden);

            if(!hidden) { //显示
            mDataBinding.taskRecyclerView.scrollToPosition(0);
            mDataBinding.banner.startAutoPlay();
            mDataBinding.toolbar.requestFocus();
            refreshAllData();
        }
        else{
            mDataBinding.banner.stopAutoPlay();
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onPause() {
        mDataBinding.banner.stopAutoPlay();
        MyLogCat.i(TAG,"onPause");
        super.onPause();
    }

    @Override
    public void onResume() {
        mDataBinding.banner.startAutoPlay();
        if(MainActivity.mCurTabIndex == 0) {
            refreshAllData();
        }
        MyLogCat.i(TAG,"onResume");
        super.onResume();
    }

    /**
     * 初始化任务列表控件
     */
    public void initRecyclerview() {
        //配置任务列表控件Recyclerview,不需要下拉刷新，因为整个页面已经有了下拉刷新
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);

        mDataBinding.taskRecyclerView.setLayoutManager(linearLayoutManager);
        mDataBinding.taskRecyclerView.setNestedScrollingEnabled(false);
        mDataBinding.taskRecyclerView.setSwipeItemClickListener(mItemClickListener); // RecyclerView Item点击监听。
        mDataBinding.taskRecyclerView.useDefaultLoadMore(); // 使用默认的加载更多的View。
        mDataBinding.taskRecyclerView.setLoadMoreListener(mLoadMoreListener); // 加载更多的监听。
        TextView header = new TextView(getActivity());
        header.setText("新任务");
        //gxw-mDataBinding.taskRecyclerView.addHeaderView(header);
        int curTaskState = mCurTaskItem != null ? mCurTaskItem.taskStatus : -2;
        mAdapter = new TaskListAdapter(mContext,curTaskState);
        mDataBinding.taskRecyclerView.setAdapter(mAdapter);
    }

    /**
     * 隐藏显示 货物类型，重量
     * @param isHidden
     */
    public void hiddenGoosType(boolean isHidden){
        if(isHidden){
            mDataBinding.tvGoodsName.setVisibility(View.GONE);
            mDataBinding.tvWeight.setVisibility(View.GONE);
        }
        else{
            mDataBinding.tvGoodsName.setVisibility(View.VISIBLE);
            mDataBinding.tvWeight.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 显示 "未接任务" 阶段的UI
     */
    public void showNoTaskStep() {
       //空闲中
    }
    /**
     * 显示 "已接任务" 阶段的UI
     */
    public void showHasRecvTaskStep() {
        //显示物流进度
        mDataBinding.stepView.setSelectPosition(0);
        mDataBinding.taskInfoLayout.setVisibility(View.VISIBLE);
        hiddenGoosType(false);
        mDataBinding.completeLayout.setVisibility(View.GONE);
        mDataBinding.welcomeLayout.setVisibility(View.GONE);
    }

    /**
     * 显示“运输”状态下的UI
     */
    public void showTransportStep() {
        mDataBinding.welcomeLayout.setVisibility(View.GONE);
        mDataBinding.stepView.setSelectPosition(2);
        mDataBinding.taskInfoLayout.setVisibility(View.VISIBLE);
        hiddenGoosType(false);
        mDataBinding.completeLayout.setVisibility(View.GONE);
    }

    /**
     * 显示 “已扫码” 提货
     */
    public void showHasGetGoodsStep() {
        mDataBinding.stepView.setSelectPosition(1);
        mDataBinding.tvCompleteTimeLabel.setVisibility(View.GONE);
        mDataBinding.tvCompleteTime.setVisibility(View.GONE);
    }

    /**
     * 显示"已完成"状态的任务进度
     */
    public void showHasCompleteStep() {
        mDataBinding.taskInfoLayout.setVisibility(View.VISIBLE);
        mDataBinding.welcomeLayout.setVisibility(View.GONE);
        mDataBinding.stepView.setSelectPosition(4);
        mDataBinding.completeLayout.setVisibility(View.VISIBLE);
        hiddenGoosType(true);
    }

    /**
     * 更新汽车状态图片 与 状态文字
     * @param strId: 状态文字id
     * @param drawableId: 汽车状态图片id
     */
    public void updateCarImv(int strId, int drawableId){
        mDataBinding.tvCarState.setText(strId);
        mDataBinding.imvCar.setImageResource(drawableId);
    }
    /**
     *根据任务状态刷新任务进度
     * @param taskItem: 任务状态
     */
    private void refreshProgressByState(int taskStatus,TaskItem taskItem) {
        WeakReference<Context> weakReference = new WeakReference<Context>(getActivity());
            switch (taskStatus) {
                case -2:  //第一次使用APP，任务信息栏显示“欢迎”
                    MyApplication.mLocationService.stop();
                    showWelcomeStep();
                    updateCarImv(R.string.idle,R.drawable.car_idle);
                    break;
                case 0: //未接任务（空闲中），目前到达不了这个状态，被已完成（空闲中）代替
                    //停止定位
                    stopLocation(taskItem.id);
                    showNoTaskStep();
                    updateCarImv(R.string.idle,R.drawable.car_idle);
                    break;
                case 9: //出卡状态
                case 1: //已接任务
                    updateCarImv(R.string.doing,R.drawable.car_moving);
                    showHasRecvTaskStep();
                    updateGoodsTypeUI(taskItem.goodsName,taskItem.weight,taskItem.unit);
                    break;
                case 2: //已提货-运输
                    updateCarImv(R.string.doing,R.drawable.car_moving);
                    showTransportStep();
                    mDataBinding.tvCarState.setText(R.string.doing);
                    updateGoodsTypeUI(taskItem.goodsName,taskItem.weight,taskItem.unit);
                    break;
                case 3: //已提交磅单
                case 4://重新提交磅单
                case 5: //已完成  ,空闲中
                    updateCarImv(R.string.has_complete,R.drawable.car_idle);
                    MyApplication.mLocationService.stop();
                    showHasCompleteStep();
                    long endTime = taskItem.endTime;
                    mDataBinding.tvCompleteTime.setText(DateTimeUtils.timeStampToDateString(endTime));
                    break;
                case 6://提货超时
                case 8: //任务过期
                case 7: //任务已撤销（提货前才能撤销）
                    stopLocation(taskItem.id);
                    showWelcomeStep();
                    break;
            }
        //来往客户名称
        if(taskItem != null) {
            mDataBinding.tvLoadCityArea.setText(taskItem.laName);
            mDataBinding.tvUnloadCity.setText(taskItem.uaName);
           // mDataBinding.tvUnloadCity.setText(MyConstant.testCustomName);//gxw要恢复
        }
    }

    /**
     * 停止定位
     */
    public void stopLocation(String taskId){
        WeakReference<Context> contextWeakReference = new WeakReference<>(mContext);
        MyApplication.getInstance().saveCurTask(contextWeakReference.get(), taskId,"0","0");
        MyApplication.mLocationService.stop();
    }
    public void updateGoodsTypeUI(String goodsName,String goodsWeight,String unit) {
        mDataBinding.tvGoodsName.setText(goodsName);
        mDataBinding.tvWeight.setText(goodsWeight+unit);
    }
    /**
     * 进度栏那里显示 “欢迎”
     */
    private void showWelcomeStep() {
        mDataBinding.taskInfoLayout.setVisibility(View.GONE);
        mDataBinding.welcomeLayout.setVisibility(View.VISIBLE);

    }

    /**
     * 第一次加载数据或下拉刷新
     */
    private void refreshTaskList() {
        pageNum = 0;
        currentOperate = PULL_REFRESH;
        String taskStatusParam= "0";
        mViewModel.getTaskList(taskStatusParam, pageNum, pageSize,0);
    }

    /**
     * Item点击监听
     */
    private SwipeItemClickListener mItemClickListener = new SwipeItemClickListener() {
        @Override
        public void onItemClick(View itemView, int position) {
            TaskItem taskItem =  mTaskList.get(position);
            String id = taskItem.getId();
            if(id != null) {
                Intent i = new Intent(mContext, TaskDetailActivity.class);
                i.putExtra("id",id);
                startActivity(i);
            }
        }
    };

    /**
     * 监听AppBar折叠还是展开
     */
    public abstract static class AppBarLayoutStateChangeListener implements AppBarLayout.OnOffsetChangedListener{
        enum State{
            EXPANDED,//展开
            COLLAPSED,//折叠
            INTERMEDIATE//中间状态
        }
        public static State mCurrentState = State.INTERMEDIATE;

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            if (verticalOffset == 0) {
                if (mCurrentState != State.EXPANDED) {
                    onStateChanged(appBarLayout, State.EXPANDED);
                }
                mCurrentState = State.EXPANDED;
            } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                if (mCurrentState != State.COLLAPSED) {
                    onStateChanged(appBarLayout, State.COLLAPSED);
                }
                mCurrentState = State.COLLAPSED;
            } else {
                if (mCurrentState != State.INTERMEDIATE) {
                    onStateChanged(appBarLayout, State.INTERMEDIATE);
                }
                mCurrentState = State.INTERMEDIATE;
            }
            //MyLogCat.i(TAG+"_home","mCurrentState="+mCurrentState+",verticalOffset="+verticalOffset);
        }
        public abstract void onStateChanged(AppBarLayout appBarLayout, State state);
    }


    /**
     * 上拉时加载更多
     */
    private SwipeMenuRecyclerView.LoadMoreListener mLoadMoreListener = new SwipeMenuRecyclerView.LoadMoreListener() {
        @Override
        public void onLoadMore() {
            currentOperate = LOAD_MORE;
            mDataBinding.taskRecyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //未开始任务列表
                    homeViewModel.getTaskList("0",pageNum,pageSize,0);
                }
            }, 2000);
        }
    };
    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {
        homeViewModel.getTaskListLiveData().observe(getViewLifecycleOwner(), new Observer<Result<JsonTaskListData>>() {
            @Override
            public void onChanged(Result<JsonTaskListData> jsonTaskListDataResult) {
                jsonTaskListDataResult.handler(new OnCallback<JsonTaskListData>() {
                    @Override
                    public void onSuccess(JsonTaskListData data) {
                        if(currentOperate == PULL_REFRESH) {
                            dealTaskListForRefresh(data);
                        }
                        else if(currentOperate == LOAD_MORE) {  //上拉加载更多
                            dealTaskListForLoadMore(data);
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        super.onError(throwable);
                        String loadErroMsg = getResources().getString(R.string.recycler_swipe_load_error);
                        mDataBinding.taskRecyclerView.loadMoreError(0,loadErroMsg);
                    }
                    @Override
                    public void onFailure(String msg) {
                        super.onFailure(msg);
                        String loadErroMsg = getResources().getString(R.string.recycler_swipe_load_error);
                        mDataBinding.taskRecyclerView.loadMoreError(0,loadErroMsg);
                    }
                });
            }
        });

        //监听当前正在进行的任务的接口
        homeViewModel.getCurTaskLiveData().observe(getViewLifecycleOwner(), new Observer<Result<TaskItem>>() {
            @Override
            public void onChanged(Result<TaskItem> jsonTaskListDataResult) {

                jsonTaskListDataResult.handler(new OnCallback<TaskItem>() {
                    @Override
                    public void onSuccess(TaskItem data) {
                        updateCurTask(data);
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        super.onError(throwable);
                    }
                    @Override
                    public void onFailure(String msg) {
                        super.onFailure(msg);
                    }
                });
            }
        });

        homeViewModel.getUnReadNumLiveData().observe(getViewLifecycleOwner(), new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> result) {
                result.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String unReadNum) {
                        int unRead = Integer.valueOf(unReadNum);
                        if(unRead > 0) {
                            mDataBinding.tvMsgBadge.setVisibility(View.VISIBLE);
                            mDataBinding.tvMsgBadge.setText(unReadNum);
                        }
                        else{
                            mDataBinding.tvMsgBadge.setVisibility(View.GONE);
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        super.onError(throwable);
                    }
                    @Override
                    public void onFailure(String msg) {
                        super.onFailure(msg);
                    }
                });
            }
        });
    }


    /**
     * 启动后台服务
     */
    public void startService() {
        if (Build.VERSION.SDK_INT >= 26) {
            Intent bleSvcIntent = new Intent(getActivity(), SocketService.class);
            getActivity().startForegroundService(bleSvcIntent);
        } else {
            Intent bleSvcIntent = new Intent(getActivity(), SocketService.class);
            getActivity().startService(bleSvcIntent);
        }
    }

    /**
     * 更新当前任务在首页中要显示的信息
     */
    public void updateCurTask(TaskItem taskItem) {
            if(taskItem != null && taskItem.id != null) {  //曾经接过任务
                mCurTaskItem = taskItem;
                mCarNum = mCurTaskItem.getVehiclePlateNumber();
                //保存起来，地图页面就不用重新请求 “当前正在进行的任务”接口了
                WeakReference<Context> contextWeakReference = new WeakReference<>(getActivity());
                //保存当前任务信息
                MyApplication.getInstance().saveCurTask(contextWeakReference.get(), taskItem.id,taskItem.upLocation,taskItem.weighsStatus);
                //更新任务进度
                refreshProgressByState(mCurTaskItem.taskStatus,taskItem);

                 //判断是否开始定位
                if("1".equals(taskItem.upLocation) && "3".equals(taskItem.weighsStatus)){   //1表示该任务需要传位置轨迹，3表示该任务出厂榜单已上传，两者都满足则定位
                    startService(); //去启动长连接
                    MyApplication.mLocationService.start();
                }
                else{//其余情况下停止定位
                    stopSocketService(); //关闭长连接
                    stopLocation(taskItem.id);//关闭定位
                }
            }
            else{ //从来没有接过任务
                int curTaskState = -2;
                refreshProgressByState(curTaskState,null);
            }
    }

    /**
     * 停止服务
     */
    public void stopSocketService(){
        SocketManager.getInstance(getActivity()).clear();
    }
    /**
     * 处理  "下拉刷新" 时 从服务器获取到的 “任务列表”，显示到 UI列表上
     * @param taskListData： “任务列表”数据
     */
    public void dealTaskListForRefresh(JsonTaskListData taskListData)
    {
        //是否有下一页
        int totalpages = taskListData.getTotalPages();
        boolean isHasMore = ((pageNum + 1) < totalpages)? true:false;
        List<TaskItem> taskItemList =  taskListData.getContent();
        boolean isCurEmptyData = true;
        mTaskList.clear();

        if(taskItemList != null && taskItemList.size() > 0) {
            mDataBinding.taskRecyclerView.setVisibility(View.VISIBLE);
            mDataBinding.noDataLayout.setVisibility(View.GONE);
            isCurEmptyData = false;
            isTaskListEmpty = false;
            mTaskList.addAll(taskItemList);
            mAdapter.notifyDataSetChanged(mTaskList);
        }
        else{
            isTaskListEmpty = true;
            mDataBinding.taskRecyclerView.setVisibility(View.GONE);
            mDataBinding.noDataLayout.setVisibility(View.VISIBLE);
        }

        if(isHasMore) { //还有更多数据时，页码+1 准备请求下一页
            pageNum++;
        }
        mDataBinding.taskRecyclerView.loadMoreFinish(isCurEmptyData, isHasMore);
    }


    /**
     * 处理  "上滑加载更多" 时 从服务器获取到的 “任务列表”，显示到 UI列表上
     * @param taskListData： “任务列表”数据
     */
    public void dealTaskListForLoadMore(JsonTaskListData taskListData)
    {
        //是否有下一页
        int totalpages = taskListData.getTotalPages();
        boolean isHasMore = ((pageNum + 1) < totalpages)? true:false;
        boolean isCurEmptyData = true;
        List<TaskItem> taskItemList =  taskListData.getContent();

        if(taskItemList != null) {
            int existSize = mTaskList.size();  //已有的条目个数
            isCurEmptyData = false;
            isTaskListEmpty = false;
            mTaskList.addAll(taskItemList);
            mAdapter.notifyItemRangeInserted(existSize - 1,taskItemList.size());
        }
        else{
            isTaskListEmpty = true;
        }
        if(isHasMore) { //还有更多数据时，页码+1 准备请求下一页
            pageNum++;
        }
        mDataBinding.taskRecyclerView.loadMoreFinish(isCurEmptyData, isHasMore);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.curTaskLayout:
                //正在进行的任务详情
                if(mCurTaskItem != null) {
                    String curTaskId = mCurTaskItem.getId();
                    Intent intent = new Intent(getActivity(), TaskDetailActivity.class);
                    intent.putExtra("id",curTaskId);
                    startActivity(intent);
                }
                break;
            case R.id.btDoTask:
                if(mTaskList != null && mTaskList.size() > 0){
                    isTaskListEmpty = false;
                }
                BottomNavigationBar bottomNavigationBar =  getActivity().findViewById(R.id.bottom_navigation_bar);
                bottomNavigationBar.selectTab(1,true);
                break;
            case R.id.tvQrCode:
                int curState = mCurTaskItem != null ? mCurTaskItem.taskStatus : -2;
                goQrCodeActivity(curState);
                break;
            case R.id.tvPostPounds:
                int curTaskState = mCurTaskItem != null ? mCurTaskItem.taskStatus : -2;
                goPostPoundsList(curTaskState);
                break;
            case R.id.tvSettings:
                Intent intent = new Intent(getActivity(), SettingsActivity.class);
                startActivity(intent);
                break;
            case R.id.msgCenterLayout: //消息中心
                Intent intentMsg = new Intent(getActivity(), MsgCenterActivity.class);
                startActivity(intentMsg);
                break;
        }
    }

    /**
     * 去二维码页面
     * @param curTaskState
     */
    public void goQrCodeActivity(int curTaskState)
    {
        WeakReference<Context> contextWeakReference = new WeakReference<>(getActivity());
        switch (curTaskState) {

            case -2:  //还没有接受过任务
                String qrNoRecvTask = this.getResources().getString(R.string.qr_no_recv_task);
                MyToast.showToastCenter(contextWeakReference,qrNoRecvTask,Toast.LENGTH_SHORT,true);
                break;
            case 1:  //已接受任务
                Intent i = new Intent(getActivity(), QrcodeActivity.class);
                if(mCurTaskItem != null) {
                    i.putExtra("taskItem", (Parcelable) mCurTaskItem);
                }
                startActivity(i);
                break;
            case 2:
                String qrHasGetGoods = this.getResources().getString(R.string.qr_has_get_goods);
                MyToast.showToastCenter(contextWeakReference,qrHasGetGoods,Toast.LENGTH_SHORT,true);
                break;
            case 3: //磅单已提交
            case 4: //重新提交磅单
            case 5:
                String qrHasGet = this.getResources().getString(R.string.qr_has_get_goods);
                MyToast.showToastCenter(contextWeakReference,qrHasGet,Toast.LENGTH_SHORT,true);
                break;
            case 6://提货超时
            case 8: //任务过期
            case 7: //任务已撤销（提货前才能撤销）
                break;
        }

    }
    /**
     * 去上传磅单
     * @param curTaskState：当前任务状态
     */
    public void goPostPoundsList(int curTaskState) {
        WeakReference<Context> contextWeakReference = new WeakReference<>(getActivity());
        switch (curTaskState) {
            case 2:
                Intent intentPounds = new Intent(getActivity(), PostPoundsListActivity.class);
                intentPounds.putExtra("taskId",mCurTaskItem.id);
                intentPounds.putExtra("taskNo",mCurTaskItem.taskNo);
                intentPounds.putExtra("unit",mCurTaskItem.unit);
                intentPounds.putExtra("carNum",mCarNum);
                intentPounds.putExtra("fromPage",1);
                startActivity(intentPounds);
                break;
            case -2:  //还没有接受过任务
            case 1:
                String qrHasGet = this.getResources().getString(R.string.un_get_goods);
                MyToast.showToastCenter(contextWeakReference,qrHasGet,Toast.LENGTH_SHORT,true);
                break;
            case 3: //磅单已提交
            case 4: //重新提交磅单
            case 5:
                String allPoundsHasUpload = this.getResources().getString(R.string.pounds_has_post);
                MyToast.showToastCenter(contextWeakReference,allPoundsHasUpload,Toast.LENGTH_SHORT,true);
                break;
            case 6://提货超时
            case 8: //任务过期
            case 7: //任务已撤销（提货前才能撤销）
                break;
        }
    }

}